import React, { useEffect } from 'react';
import { View, StyleSheet, ScrollView, Share } from 'react-native';
import { Card, Title, Paragraph, Button, ActivityIndicator, Text } from 'react-native-paper';
import { useRoute } from '@react-navigation/native';
import { useQuery } from '@tanstack/react-query';
import Toast from 'react-native-toast-message';
import * as FileSystem from 'expo-file-system';
import * as Sharing from 'expo-sharing';

import { ColorizeService } from '../services/api';
import { useColorizeStore } from '../store/colorizeStore';

export function ResultScreen({ navigation }: any) {
  const route = useRoute<any>();
  const { taskId } = route.params;
  const { updateTask } = useColorizeStore();

  const { data: taskStatus, isLoading, error, refetch } = useQuery({
    queryKey: ['taskStatus', taskId],
    queryFn: () => ColorizeService.getTaskStatus(taskId),
    refetchInterval: (data) => {
      if (data?.status === 'completed' || data?.status === 'failed') {
        return false;
      }
      return 2000; // Poll every 2 seconds
    },
  });

  useEffect(() => {
    if (taskStatus?.status === 'completed' && taskStatus.result) {
      updateTask(taskId, {
        status: 'completed',
        coloredImage: taskStatus.result.colored_image_url,
        completedAt: new Date().toISOString(),
      });
    } else if (taskStatus?.status === 'failed') {
      updateTask(taskId, {
        status: 'failed',
        error: taskStatus.result?.error_message || 'Processing failed',
      });
    }
  }, [taskStatus, taskId, updateTask]);

  const handleDownload = async () => {
    if (!taskStatus?.result?.colored_image_url) return;

    try {
      const filename = `colorized_${taskId}.png`;
      const fileUri = `${FileSystem.documentDirectory}${filename}`;
      
      await FileSystem.downloadAsync(
        taskStatus.result.colored_image_url,
        fileUri
      );
      
      if (await Sharing.isAvailableAsync()) {
        await Sharing.shareAsync(fileUri);
      }
      
      Toast.show({
        type: 'success',
        text1: 'Image saved',
        text2: 'Image has been saved to your device',
      });
    } catch (error) {
      Toast.show({
        type: 'error',
        text1: 'Download failed',
        text2: 'Could not save the image',
      });
    }
  };

  const handleShare = async () => {
    if (!taskStatus?.result?.colored_image_url) return;

    try {
      await Share.share({
        message: `Check out my AI-colored manga! ${taskStatus.result.colored_image_url}`,
        url: taskStatus.result.colored_image_url,
      });
    } catch (error) {
      Toast.show({
        type: 'error',
        text1: 'Share failed',
        text2: 'Could not share the image',
      });
    }
  };

  if (isLoading) {
    return (
      <View style={styles.container}>
        <ActivityIndicator size="large" />
        <Text>Loading task status...</Text>
      </View>
    );
  }

  if (error) {
    return (
      <View style={styles.container}>
        <Text>Error loading task status</Text>
        <Button onPress={() => refetch()}>Retry</Button>
      </View>
    );
  }

  if (!taskStatus) {
    return (
      <View style={styles.container}>
        <Text>No task data available</Text>
      </View>
    );
  }

  return (
    <ScrollView style={styles.container}>
      <View style={styles.content}>
        <Card style={styles.card}>
          <Card.Content>
            <Title>Colorization Result</Title>
            <Text>Task ID: {taskId}</Text>
            <Text>Status: {taskStatus.status}</Text>
            {taskStatus.progress > 0 && (
              <Text>Progress: {taskStatus.progress}%</Text>
            )}
          </Card.Content>
        </Card>

        {taskStatus.status === 'processing' && (
          <Card style={styles.card}>
            <Card.Content>
              <ActivityIndicator size="large" />
              <Text style={styles.centerText}>Processing your image...</Text>
            </Card.Content>
          </Card>
        )}

        {taskStatus.status === 'failed' && (
          <Card style={styles.card}>
            <Card.Content>
              <Text style={styles.errorText}>
                {taskStatus.result?.error_message || 'Processing failed'}
              </Text>
              <Button onPress={() => navigation.goBack()}>Try Again</Button>
            </Card.Content>
          </Card>
        )}

        {taskStatus.status === 'completed' && taskStatus.result && (
          <>
            <Card style={styles.card}>
              <Card.Cover 
                source={{ uri: taskStatus.result.original_image_url }} 
                style={styles.image}
              />
              <Card.Content>
                <Title>Original Sketch</Title>
              </Card.Content>
            </Card>

            <Card style={styles.card}>
              <Card.Cover 
                source={{ uri: taskStatus.result.colored_image_url }} 
                style={styles.image}
              />
              <Card.Content>
                <Title>Colored Result</Title>
                <Paragraph>
                  Processing time: {taskStatus.result.processing_time?.toFixed(2)}s
                </Paragraph>
                {taskStatus.result.metadata && (
                  <Paragraph>
                    Style: {taskStatus.result.metadata.style}
                  </Paragraph>
                )}
              </Card.Content>
            </Card>

            <View style={styles.buttonContainer}>
              <Button 
                mode="contained" 
                onPress={handleDownload}
                icon="download"
                style={styles.button}
              >
                Download
              </Button>
              <Button 
                mode="outlined" 
                onPress={handleShare}
                icon="share"
                style={styles.button}
              >
                Share
              </Button>
              <Button 
                mode="outlined" 
                onPress={() => navigation.navigate('Home')}
                style={styles.button}
              >
                Colorize Another
              </Button>
            </View>
          </>
        )}
      </View>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  content: {
    padding: 16,
  },
  card: {
    marginBottom: 16,
  },
  image: {
    height: 300,
    resizeMode: 'contain',
  },
  buttonContainer: {
    gap: 12,
    marginTop: 20,
  },
  button: {
    marginVertical: 4,
  },
  centerText: {
    textAlign: 'center',
    marginTop: 10,
  },
  errorText: {
    color: 'red',
    textAlign: 'center',
  },
});
